package consume.listener;

import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;

/**
 * @author Kevin
 * @date 2023/6/11 12:46
 * @description 路由模式消息
 **/
@Slf4j
@Component
public class RoutingListener {

  /**
   * 需要绑定对应路由key的交换机
   * 注意交换机类型为direct
   *
   * @param msg 接收到的消息
   * @param deliveryTag 手动签收所需参数
   * @param channel     手动签收所需参数
   */
  @RabbitListener(bindings = @QueueBinding(value = @Queue,
          exchange = @Exchange(value = "routing-exchange", type = "direct"),
          key = {"info", "error"}))
  public void listener1(String msg,
                        @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag,
                        Channel channel) throws Exception {

    // 手动签收
    channel.basicAck(deliveryTag, true);

    log.info("消费者1监听到路由消息--{}", msg);
  }

  /**
   * 需要绑定对应路由key的交换机
   * 注意交换机类型为direct
   *
   * @param msg 接收到的消息
   * @param deliveryTag 手动签收所需参数
   * @param channel     手动签收所需参数
   */
  @RabbitListener(bindings = @QueueBinding(value = @Queue,
          exchange = @Exchange(value = "routing-exchange", type = "direct"),
          key = {"trance", "waring"}))
  public void listener2(String msg,
                        @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag,
                        Channel channel) throws Exception {

    // 手动签收
    channel.basicAck(deliveryTag, true);

    log.info("消费者2监听到路由消息--{}", msg);
  }


}
